package com.klod.data.repository

import com.klod.data.mapping.*
import com.klod.ext.suspendTransaction
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
import org.koin.core.annotation.Single


interface NewsRepositoryI {


    suspend fun findAllNews(type: String, page: Int, pageSize: Int): MutableList<NewsDetailBean>


    suspend fun findNewsById(id: Int): NewsDetailBean?

    suspend fun addNews(task: NewsDetailBean): Int

    suspend fun removeNews(id: Int): Boolean

    suspend fun types(): List<NewsTypeBean>

}


@Single
class NewsRepository : NewsRepositoryI {


    override suspend fun findAllNews(type: String, page: Int, pageSize: Int): MutableList<NewsDetailBean> =
        suspendTransaction {
//        BannersDAO.all().map(::daoToModel).toMutableList()


            val q = NewsTable.selectAll()
            if (type.isNotBlank()) {
                //添加type判断
                q.adjustWhere { NewsTable.type eq type }
            }
            //添加分页
            q.limit(pageSize).offset((page - 1) * pageSize.toLong())
                .map(::daoToNewsDetailModel).toMutableList()


//            NewsTable.selectAll().map(::daoToNewsDetailModel).toMutableList()
        }
//    override suspend fun findAllNewsByType(type :String): MutableList<NewsDetailBean> = suspendTransaction {
////        BannersDAO.all().map(::daoToModel).toMutableList()
//        NewsTable.selectAll().where{
//            (NewsTable.type eq type)
//        }.map(::daoToNewsDetailModel).toMutableList()
//    }

    override suspend fun findNewsById(id: Int): NewsDetailBean? = suspendTransaction {
//        BannersDAO.find { (NewsTable.bId eq bId) }
//            .limit(1)
//            .map(::daoToModel)
//            .firstOrNull()
        NewsTable.selectAll()
            .where { NewsTable.id eq id }
            .map(::daoToNewsDetailModel)
            .singleOrNull()
    }

    override suspend fun addNews(task: NewsDetailBean): Int = suspendTransaction {
//        BannersDAO.new {
////            bId = task.bId
//            imgUrl = task.imageUrl
//            content = task.content
//        }.let(::daoToModel )

//        NewsTable.insert {
//
//        } get NewsTable.bId
        NewsTable.insert {
            it[title] = task.title
            it[content] = task.content
            it[date] = task.date
            it[type] = task.type
        }[NewsTable.id]
//
    }

    override suspend fun removeNews(id: Int): Boolean = suspendTransaction {
        NewsTable.deleteWhere {
            (NewsTable.id eq id)
        } == 1
    }

    override suspend fun types(): List<NewsTypeBean> = suspendTransaction{

        NewsTypeTable.selectAll().map(::daoToNewsTypeModel).toMutableList()

    }
}